package com.example.orderservice.controller;

import com.example.common.response.Result;
import com.example.orderservice.entity.Order;
import com.example.orderservice.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderRepository orderRepository;

    @GetMapping
    public Result<List<Order>> getAllOrders() {
        List<Order> orders = orderRepository.findAll();
        return Result.success(orders);
    }

    @GetMapping("/{id}")
    public Result<Order> getOrderById(@PathVariable Long id) {
        Order order = orderRepository.findById(id).orElse(null);
        if (order != null) {
            return Result.success(order);
        }
        return Result.error("订单不存在");
    }

    @GetMapping("/user/{userId}")
    public Result<List<Order>> getOrdersByUserId(@PathVariable Long userId) {
        List<Order> orders = orderRepository.findByUserId(userId);
        return Result.success(orders);
    }

    @PostMapping
    public Result<Order> createOrder(@RequestBody Order order) {
        // 生成订单号
        order.setOrderNumber("ORD" + UUID.randomUUID().toString().substring(0, 8).toUpperCase());
        order.setStatus("PENDING");
        Order savedOrder = orderRepository.save(order);
        return Result.success(savedOrder);
    }

    @PutMapping("/{id}")
    public Result<Order> updateOrder(@PathVariable Long id, @RequestBody Order order) {
        if (orderRepository.existsById(id)) {
            order.setId(id);
            Order updatedOrder = orderRepository.save(order);
            return Result.success(updatedOrder);
        }
        return Result.error("订单不存在");
    }

    @DeleteMapping("/{id}")
    public Result<String> deleteOrder(@PathVariable Long id) {
        if (orderRepository.existsById(id)) {
            orderRepository.deleteById(id);
            return Result.success("订单删除成功");
        }
        return Result.error("订单不存在");
    }
}
